%%--------------------------------------------------------------------
%% Copyright (c) 2013-2017 EMQ Enterprise, Inc. (http://emqtt.io)
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%     http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------

-module(emq_auth_demo).

-behaviour(emqttd_auth_mod).

-include_lib("emqttd/include/emqttd.hrl").

-export([init/1, check/3, description/0]).

init(Opts) -> {ok, Opts}.

check(#mqtt_client{client_id = ClientId, username = Username}, Password, _Opts) ->
%%    {ok, C} = eredis:start_link("192.168.1.145", 6379, 0, "redis"),
    {ok, C} = eredis:start_link("139.224.57.152", 6379, 0, "7fcb6fd7be367b92a351b29504183750"),
    IdLength = length(binary_to_list(ClientId)),
    io:format("ClientId:~p~n", [ClientId]),
    io:format("IdLength:~p~n", [IdLength]),
    %% Select client_id in redis
    Value = case IdLength of
        32 -> eredis:q(C, ["HEXISTS", "user", ClientId]);
        10 -> eredis:q(C, ["HEXISTS", "device", ClientId]);
        _ -> io:format("client is not exist")
    end,
    %% Authentication client
    io:format("Values:~p~n", [Value]),
    case Value of
        {ok,<<"1">>} when IdLength =:= 32; IdLength =:= 10 ->
            io:format("Auth Demo: clientId=~p, username=~p, password=~p~n", [ClientId, Username, Password]);
        {ok,<<"0">>} ->
            io:format("client is error. ~n"),
            esockd:deny();
        _ ->
            io:format("client is not exist. ~n"),
            esockd:deny()
    end,
    ok.

description() -> "Auth Demo Module".
